import React, { useState, KeyboardEvent } from 'react';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';

interface TagInputProps {
    value: string[];
    onChange: (tags: string[]) => void;
    placeholder?: string;
    className?: string;
    disabled?: boolean;
    /** Transform input before adding (e.g., toUpperCase for Jira project keys) */
    transformInput?: (value: string) => string;
}

/**
 * TagInput - A component for entering multiple tags/items
 * 
 * Features:
 * - Add tags by pressing Enter or comma
 * - Remove tags by clicking X or pressing Backspace on empty input
 * - Visual feedback for dark/light themes
 * - Keyboard accessible
 */
export const TagInput: React.FC<TagInputProps> = ({
    value = [],
    onChange,
    placeholder = 'Type and press Enter...',
    className,
    disabled = false,
    transformInput,
}) => {
    const [inputValue, setInputValue] = useState('');

    const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
        // Add tag on Enter or comma
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            addTag();
        }
        // Remove last tag on Backspace if input is empty
        else if (e.key === 'Backspace' && !inputValue && value.length > 0) {
            removeTag(value.length - 1);
        }
    };

    const addTag = () => {
        let trimmedValue = inputValue.trim();
        if (trimmedValue) {
            // Apply transformation if provided (e.g., uppercase for Jira keys)
            if (transformInput) {
                trimmedValue = transformInput(trimmedValue);
            }
            // Check for duplicates after transformation
            if (!value.includes(trimmedValue)) {
                onChange([...value, trimmedValue]);
                setInputValue('');
            } else {
                // Still clear input if it's a duplicate
                setInputValue('');
            }
        }
    };

    const removeTag = (indexToRemove: number) => {
        onChange(value.filter((_, index) => index !== indexToRemove));
    };

    const handleInputBlur = () => {
        // Add tag on blur if there's content
        if (inputValue.trim()) {
            addTag();
        }
    };

    return (
        <div
            className={cn(
                'flex flex-wrap gap-2 min-h-[42px] w-full rounded-lg border p-2',
                'bg-transparent focus-within:outline-none focus-within:border-gray-400 dark:focus-within:border-gray-600',
                'border-gray-200 dark:border-gray-800',
                disabled && 'opacity-50 cursor-not-allowed',
                className
            )}
        >
            {/* Render existing tags */}
            {value.map((tag, index) => (
                <div
                    key={index}
                    className={cn(
                        'flex items-center gap-1.5 px-2.5 py-1 rounded-md text-sm font-medium',
                        'bg-blue-50 dark:bg-slate-700 text-blue-700 dark:text-slate-100',
                        'border border-blue-200 dark:border-slate-600',
                        'transition-colors'
                    )}
                >
                    <span>{tag}</span>
                    {!disabled && (
                        <button
                            type="button"
                            onClick={() => removeTag(index)}
                            className={cn(
                                'hover:bg-blue-100 dark:hover:bg-slate-600 rounded-sm p-0.5',
                                'focus:outline-none focus:ring-1 focus:ring-blue-400 dark:focus:ring-slate-500',
                                'transition-colors'
                            )}
                            aria-label={`Remove ${tag}`}
                        >
                            <X className="h-3 w-3" />
                        </button>
                    )}
                </div>
            ))}

            {/* Input for new tags */}
            {!disabled && (
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyDown={handleKeyDown}
                    onBlur={handleInputBlur}
                    placeholder={value.length === 0 ? placeholder : ''}
                    className={cn(
                        'flex-1 min-w-[120px] bg-transparent outline-none text-sm',
                        'text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-gray-600'
                    )}
                />
            )}
        </div>
    );
};

